package com.example.duihua.controller;

import com.example.duihua.entity.User;
import com.example.duihua.service.UserService;
import com.example.duihua.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/profile")
    public ResponseEntity<?> getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        User user = userService.findByUsername(userDetails.getUsername());
        if (user != null) {
            // 不返回密码
            user.setPassword(null);
            return ResponseEntity.ok(ApiResponse.success(user));
        }
        return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(
            @RequestBody User userUpdate,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        User currentUser = userService.findByUsername(userDetails.getUsername());
        if (currentUser == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        // 只允许更新昵称和头像
        currentUser.setNickname(userUpdate.getNickname());
        if (userUpdate.getAvatar() != null) {
            currentUser.setAvatar(userUpdate.getAvatar());
        }
        
        User updatedUser = userService.updateProfile(currentUser);
        // 不返回密码
        updatedUser.setPassword(null);
        
        return ResponseEntity.ok(ApiResponse.success("资料更新成功", updatedUser));
    }

    @PutMapping("/status")
    public ResponseEntity<?> updateStatus(
            @RequestBody StatusUpdateRequest request,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        boolean success = userService.updateStatus(user.getId(), request.getStatus());
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("状态更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error("状态更新失败"));
        }
    }

    @GetMapping("/contacts")
    public ResponseEntity<?> getContacts(@AuthenticationPrincipal UserDetails userDetails) {
        User currentUser = userService.findByUsername(userDetails.getUsername());
        if (currentUser == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        // 获取所有用户作为联系人（除了自己）
        java.util.List<User> allUsers = userService.getAllUsers();
        java.util.List<User> contacts = allUsers.stream()
            .filter(user -> !user.getId().equals(currentUser.getId()))
            .peek(user -> user.setPassword(null)) // 不返回密码
            .collect(java.util.stream.Collectors.toList());
        
        return ResponseEntity.ok(ApiResponse.success(contacts));
    }
    
    // 内部类：状态更新请求
    static class StatusUpdateRequest {
        private String status;
        
        public String getStatus() {
            return status;
        }
        
        public void setStatus(String status) {
            this.status = status;
        }
    }
}